package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义类实现UserDetailsService接口 用于用户登录校验  角色和权限的授予
 * Spring Security 框架对外接口
 *
 * @author Chengfei
 * @date 2020/08/18
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return UserDetails的实现类User
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用方法,根据用户名查询用户
        com.itheima.pojo.User user = userService.findByUsername(username);

        //判断用户是否存在
        if (user == null) {
            //用户不存在
            return null;
        }
        //定义存放权限和角色的集合, 因权限有重复,所以将list集合改为set集合
        //List<GrantedAuthority> list = new ArrayList<>();
        Set<GrantedAuthority> list = new HashSet<>();

        //得到用户所有角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授予权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //构建UserDetails对象,并返回
        return new User(username, user.getPassword(), list);
    }


}
